<template>
  <!-- 上传背景图 -->
  <a-modal
    :visible="visible"
    title="设置背景图"
    centered
    @cancel="handleClose"
    @ok="handleSubmit"
    destroy-on-close
  >
    <a-upload
      :action="$utils.imgAction"
      :headers="{ 'org-token': $store.getters.token }"
      :multiple="false"
      v-model:file-list="fileList"
      list-type="picture-card"
      @change="handleUploadChange"
      name="image"
      :data="{ dir: 'org_basic_setting' }"
      accept="image/jpg,image/jpeg,image/gif,image/png"
    >
      <div v-if="!fileList.length">
        <plus-outlined></plus-outlined>
        <div>上传</div>
      </div>
    </a-upload>
  </a-modal>
</template>

<script>
import {defineComponent, reactive, toRefs, watch} from "vue";
import {Form, message} from "ant-design-vue";
import request from "@/common/utils/request";
const useForm = Form.useForm;
import _ from "lodash";
import {
  PlusOutlined,
} from "@ant-design/icons-vue";
export default defineComponent({
  name: "SettingBgModal",
  components: { PlusOutlined },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    bgUrl: {
      type: String,
      default: '',
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      fileList: [],
      url: '',
    });



    const handleClose = () => {
      emit('handleClose')
    };

    const handleUploadChange = (info) => {
      let resFileList = [...info.fileList];
      if (resFileList.length) {
        resFileList = resFileList.slice(-1);
        resFileList = resFileList.map((file) => {
          if (file.response) {
            if (file.response.code == 1000) {
              file.url = file.response.data.fileUrl;
              state.url = file.url;
            } else {
              message.warning(file.response.msg);
            }
          }
          return file;
        });
      } else {
        state.url = '';
      }
      state.fileList = resFileList;
    };

    const handleSubmit = () => {
      emit('handleSuccess', state.url);
    };

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          if (props.bgUrl) {
            state.fileList = [
              {
                uid: "1",
                name: props.bgUrl,
                status: "done",
                url: props.bgUrl,
              },
            ]
          }
          state.url = props.bgUrl;
        } else {
          state.fileList = [];
          state.url = '';
        }
      }
    );

    return {
      ...toRefs(state),
      handleClose,
      handleSubmit,
      handleUploadChange,
    };
  },
});
</script>

<style lang="less" scoped></style>
